#include "stdafx.h"
#include "CMeasureManager.h"
#include "CMeasureObj.h"

CMeasureManager::CMeasureManager()
	: m_pSelMObj(NULL)
{

}

CMeasureManager::~CMeasureManager(void)
{

}

void CMeasureManager::AddMObj(UINT pImage, CMeasureObj* pObj)
{
	if (pObj == NULL) return;

	MeasureObjList* pList = FindMeasureList(pImage);

	if (pList == NULL)
	{
		pList = new MeasureObjList;
		m_mapMeasure.insert(std::make_pair(pImage, pList));
	}

	pList->push_back(pObj);
}

CMeasureManager::MeasureObjList* CMeasureManager::FindMeasureList(UINT pImage)
{
	std::map<UINT, MeasureObjList*>::iterator itr;
	itr = m_mapMeasure.find(pImage);

	if (itr != m_mapMeasure.end())
		return itr->second;
	else
		return NULL;
}

void CMeasureManager::DeleteSel(UINT pImage)
{
	MeasureObjList* pList = FindMeasureList(pImage);
	if (pList == NULL)
		return;

	if (pList->size() <= 0)
		return;

	BOOL hasSel = FALSE;

	MOListItor itr = pList->begin();
	for (; itr != pList->end(); itr++)
	{
		if ((*itr)->GetSel())
		{
			hasSel = TRUE;
			break;
		}
	}

	if (!hasSel)
	{
		pList->back()->SetSel(TRUE);
	}

	for (itr = pList->begin(); itr != pList->end();)
	{
		if ((*itr)->GetSel())
		{
			delete (*itr);
			itr = pList->erase(itr);
			break;
		}
		else
		{
			itr++;
		}
	}
}

void CMeasureManager::Delete(UINT pImage)
{
	MeasureObjList* pList = FindMeasureList(pImage);
	for (MOListItor itr = pList->begin(); itr != pList->end();)
	{
		delete (*itr);
		itr = pList->erase(itr);
	}
	pList->clear();
}

void CMeasureManager::DeleteAll()
{
	std::map<UINT, MeasureObjList*>::iterator itr;
	for (itr = m_mapMeasure.begin(); itr != m_mapMeasure.end(); itr++)
	{
		MOListItor mitr;
		MeasureObjList *mlist = itr->second;

		for (mitr = mlist->begin(); mitr != mlist->end(); mitr++)
		{
			delete (*mitr);
		}
		mlist->clear();
	}
	m_mapMeasure.clear();
}

int CMeasureManager::HitTest(UINT pImage, Gdiplus::PointF pt, BOOL bPress /*= FALSE*/)
{
	MeasureObjList* pList = FindMeasureList(pImage);
	if (pList == NULL)
		return -1;

	int bSel = -1;

	MOListItor itr = pList->begin();
	for (; itr != pList->end(); itr++)
	{
		int code = (*itr)->HitTest(pt, bPress);
		if (bPress && code != -1)
		{
			m_pSelMObj = (*itr);
			bSel = code;
		}

	}

	if (bSel == -1)
		m_pSelMObj = NULL;

	if (bSel == 4)
	{
		itr = pList->begin();
		for (; itr != pList->end(); itr++)
		{
			if ((*itr) != m_pSelMObj)
			{
				(*itr)->SetSel(FALSE);
			}

		}
	}

	return bSel;
}

int CMeasureManager::Move(UINT pImage, Gdiplus::SizeF szOffset)
{
	if (!m_pSelMObj)
		return -1;
	return m_pSelMObj->Move(szOffset.Width, szOffset.Height);
}

void CMeasureManager::DrawMObjs(UINT pImage, HDC hDC, RECT rc, const DrawParam& drawInfo)
{
	MeasureObjList* pList = FindMeasureList(pImage);
	if (pList == NULL)
		return;

	MOListItor itr = pList->begin();
	for (; itr != pList->end(); itr++)
	{
		(*itr)->Draw(hDC, rc, drawInfo);
	}
}
